import { defineStore } from 'pinia';
import { to } from 'await-to-js';
import type { BannerList } from '@/views/Home/components/api';
import { getBannerList } from '@/views/Home/components/api';
import type { CategoryList, GoodsItem } from '@/views/Category/components/api';
import { getHomeList, getNewGoodList } from '@/views/Category/components/api';

// 定义 Store 时建议遵循命名规范 useXxxStore
const useHomeStore = defineStore('home', () => {
  const categoryList = ref<Array<CategoryList>>([]);
  const bannerList = ref<Array<BannerList>>([]);
  const newGoodsList = ref<Array<GoodsItem>>([]);

  /**
   * 获取所有分类数据
   */
  const getAllCategoryList = async (): Promise<CategoryList[]> => {
    if (categoryList.value.length > 0) {
      return categoryList.value;
    }
    const [code, res] = await to(getHomeList());
    if (res) {
      categoryList.value = res.rows;
      return categoryList.value;
    }
    return [];
  };

  /**
   * 获取所有轮播图
   */
  const getAllBannerList = async (): Promise<GoodsItem[]> => {
    if (bannerList.value.length > 0) {
      return bannerList.value;
    }
    const [code, res] = await to(getBannerList());
    if (res) {
      bannerList.value = res.rows;
      return bannerList.value;
    }
    return [];
  };

  /**
   * 获取所有商品
   */
  const getHomeNewGoodList = async (): Promise<GoodsItem[]> => {
    if (newGoodsList.value.length > 0) {
      return newGoodsList.value;
    }
    const [code, res] = await to(getNewGoodList());
    if (res) {
      newGoodsList.value = res.rows;
      return newGoodsList.value;
    }
    return [];
  };

  return {
    categoryList,
    bannerList,
    newGoodsList,
    getAllCategoryList,
    getAllBannerList,
    getHomeNewGoodList
  };
});

// 默认导出
export default useHomeStore;
